package org.example.test;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;



public class SimpleJdbcOperation {
    //先创建数据库连接池DateSource
    private final DataSource dataSource;
    //调用该方法的时候初始化
    public SimpleJdbcOperation(DataSource dataSource) {
        this.dataSource = dataSource;
    }
    //同时有一个Book内部类
    public static class Book {
        private String name;
        private String author;
        private String isbn;
        //省略 setter getter 方法
    }


    public void addBook() {
        Connection connection = null;
        PreparedStatement Statement = null;
        try {
            //1.通过DateSource获取数据库连接connection
            connection = dataSource.getConnection();
            //2.通过数据库链接connection建立命令对象Statement + 编写带？占位符的SQL语句
            Statement = connection.prepareStatement(
                    "insert into soft_bookrack (book_name, book_author, book_isbn) values (?,?,?);"
            );
            //3.替换占位符，进行参数绑定
            Statement.setString(1, "Spring in Action");
            Statement.setString(2, "Craig Walls");
            Statement.setString(3, "9787115417305");
            //4.使用Statement命令对象来执行语句
            Statement.execute();
            //5.这里如果你是在查询功能，那么你还要处理结果集进行返回
        } catch (SQLException e) {
            //处理异常信息
        } finally {
            //6.清理资源
            try {
                if (Statement != null) {
                    Statement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
            }
        }
    }

}
